package com.sls.api.game.servlet.enfu;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.sls.api.game.pojo.EnfuServerInfo;
import com.sls.api.game.servlet.SuperServlet;
import com.sls.api.util.IpUtil;
import com.sls.api.util.PropertiesUtil;
import com.sls.api.util.ResponseDataXmlFormat;
import com.sls.api.util.UtilMD5Encryption;
import com.sls.core.common.CommonUtil;
import com.sls.core.socket.Head;
import com.sls.core.socket.SocketDTO;

/**
 * 
 * @description 异步充值订单状态变化通知接口
 * @author Wangxuegang
 * @date 2013-4-28
 */
public class EnfuOrderStatusServlet extends SuperServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger.getLogger(EnfuOrderStatusServlet.class);

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setAttribute("org.eclipse.jetty.server.Request.queryEncoding",
				"GBK");
		resp.setContentType("text/html;charset=GBK");
		resp.setStatus(HttpServletResponse.SC_OK);
		log.info("恩付异步通知的请求参数：" + req.getQueryString());

		// 合作平台编号
		String partnerId = req.getParameter("partnerId");
		// 合作方平台订单编号
		String ptOrderNo = req.getParameter("ptOrderNo");
		// SUP平台订单号
		String supOrderNo = req.getParameter("supOrderNo");
		// 订单结果
		String status = req.getParameter("status");
		// SUP平台充值成功时间
		String supOrderSuccessTime = req.getParameter("supOrderSuccessTime");
		// 失败代码
		String failedCode = req.getParameter("failedCode");
		// 失败原因
		String failedReason = req.getParameter("failedReason");
		// 签名字符串
		String sign = req.getParameter("sign");

		String partnerKey = PropertiesUtil.getValue("enfu.md5.key");
		boolean flag = checkData(partnerId, ptOrderNo, supOrderNo, status,
				supOrderSuccessTime, failedCode, failedReason, sign,
				partnerKey, resp);
		if (flag) { // 数据校验通过
			try {
				Gson gson = CommonUtil.gson();
				SocketDTO socketChangeVo = createMsg(partnerId, ptOrderNo,
						supOrderNo, status, supOrderSuccessTime, failedCode,
						failedReason, sign, req);
				Head head = socketChangeVo.getHead();
				String resCode = head.getResponseCode();
				String resMsg = head.getResponseMessage();
				resMsg = URLEncoder.encode(resMsg, "GBK"); // GBK编码

				String bodyStr = socketChangeVo.getBody();
				String resBodyStr = gson.fromJson(bodyStr, String.class);

				String xmlStr = ResponseDataXmlFormat.assembleXmlStrForOrder(
						resBodyStr, resCode, resMsg, ptOrderNo);
				resp.getWriter().write(xmlStr);
				resp.getWriter().flush();
				resp.getWriter().close();
			} catch (Exception e) {
				log.error("出错", e);
				ResponseDataXmlFormat.returnResMsg("201", "其他错误", resp);
			}
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	/**
	 * 数据校验
	 * 
	 * @param partnerId
	 * @param ptOrderNo
	 * @param supOrderNo
	 * @param status
	 * @param supOrderSuccessTime
	 * @param failedCode
	 * @param failedReason
	 * @param sign
	 * @param partnerKey
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	private boolean checkData(String partnerId, String ptOrderNo,
			String supOrderNo, String status, String supOrderSuccessTime,
			String failedCode, String failedReason, String sign,
			String partnerKey, HttpServletResponse resp) throws IOException {
		boolean flag = false;
		// 合作平台编号
		if ("".equals(partnerId) || partnerId == null) {
			log.info("合作平台编号为空");
			ResponseDataXmlFormat
					.returnResMsg("101", "缺少必需参数[partnerId]", resp);
		}
		// 合作方平台订单编号
		else if ("".equals(ptOrderNo) || ptOrderNo == null) {
			log.info("合作方平台订单编号为空");
			ResponseDataXmlFormat
					.returnResMsg("101", "缺少必需参数[ptOrderNo]", resp);
		}
		// SUP平台订单号
		else if ("".equals(supOrderNo) || supOrderNo == null) {
			log.info("SUP平台订单号为空");
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[supOrderNo]",
					resp);
		}
		// 订单结果
		else if ("".equals(status) || status == null) {
			log.info("订单结果为空");
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[status]", resp);
		}
		// 签名字符串
		else if ("".equals(sign) || sign == null) {
			log.info("签名字符串为空");
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[sign]", resp);
		} else {
			StringBuilder strbu = new StringBuilder();
			if (failedCode != null && !("".equals(failedCode))) {
				strbu.append("failedCode");
				strbu.append(failedCode);
			}

			if (failedReason != null && !("".equals(failedReason))) {
				strbu.append("failedReason");
				strbu.append(failedReason);
			}
			strbu.append("partnerId");
			strbu.append(partnerId);
			strbu.append("ptOrderNo");
			strbu.append(ptOrderNo);
			strbu.append("status");
			strbu.append(status);
			strbu.append("supOrderNo");
			strbu.append(supOrderNo);

			if (supOrderSuccessTime != null
					&& !("".equals(supOrderSuccessTime))) {
				strbu.append("supOrderSuccessTime");
				strbu.append(supOrderSuccessTime);
			}
			strbu.append(partnerKey);
			String data = strbu.toString().trim();

			boolean checkRes = UtilMD5Encryption.checkMD5Signature(data, sign);
			if (checkRes) {
				flag = true;
			} else {
				log.info("MD5数字签名未通过");
				flag = false;
				ResponseDataXmlFormat.returnResMsg("102", "签名失败", resp);
			}
		}

		return flag;
	}

	/**
	 * 创建Json格式socket消息包
	 * 
	 * @param partnerId
	 * @param ptOrderNo
	 * @param supOrderNo
	 * @param status
	 * @param supOrderSuccessTime
	 * @param failedCode
	 * @param failedReason
	 * @param sign
	 * @param req
	 * @return
	 */
	private SocketDTO createMsg(String partnerId, String ptOrderNo,
			String supOrderNo, String status, String supOrderSuccessTime,
			String failedCode, String failedReason, String sign,
			HttpServletRequest req) {
		EnfuServerInfo enfuServerInfo = new EnfuServerInfo();
//		enfuServerInfo.setPartnerId(partnerId);
//		enfuServerInfo.setPtOrderNo(ptOrderNo);
//		enfuServerInfo.setSupOrderNo(supOrderNo);
//		enfuServerInfo.setStatus(status);
//		enfuServerInfo.setSupOrderSuccessTime(supOrderSuccessTime);
//		enfuServerInfo.setFailedCode(failedCode);
//		enfuServerInfo.setFailedReason(failedReason);
//		enfuServerInfo.setSign(sign);

		SocketDTO socketChangeVo = new SocketDTO();
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(""); // ==============================?????????????????待完善
		head.setIp(IpUtil.getIpAddr(req)); // ---------坚果网络IP
		head.setUserId("0"); // ---------坚果网络用户ID
		socketChangeVo.setHead(head); // 报文头部
		return super.send(head, enfuServerInfo);
	}

}
